<template>
  <div class="">
    <!-- head -->
    <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑优惠券" : "新增优惠券" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix>
    <!-- head end -->
    <div class="card mt10">
      <el-form :model="couponForm" label-width="175px" :rules="couponRules" ref="ruleFormRef">
        <!-- 基础信息 -->
        <div class="group">
          <div class="section-title">基础信息</div>
          <el-form-item label="券类型" prop="typeId">
            <el-radio-group v-model="couponForm.typeId" @change="changeTypeId">
              <el-radio :disabled="route.query.id" v-for="item in couponType" :key="item.value" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="券名称" prop="name">
            <el-input v-model="couponForm.name" placeholder="请填写优惠券名称" style="width: 320px"></el-input>
          </el-form-item>
          <el-form-item :label="couponForm.typeId === 1 ? '券面值' : '券折扣'" prop="parValue" v-if="couponForm.typeId !== 2">
            <el-input-number
              v-model="couponForm.parValue"
              :min="1"
              :max="couponForm.typeId === 1 ? 99999 : 99"
              :controls="false"
              style="width: 320px"
            />
            <el-text class="ml10">{{ couponForm.typeId === 1 ? "元" : "% 打7七折,请填写70" }}</el-text>
          </el-form-item>
          <el-form-item label="使用有效期类型" prop="validityType">
            <el-radio-group v-model="couponForm.validityType">
              <el-radio :label="0">自定义日期</el-radio>
              <el-radio :label="1">相对有效期</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自定义日期" prop="validityObject" v-if="couponForm.validityType === 0">
            <div>
              <el-date-picker
                class="width300"
                v-model="couponForm.validityObject"
                type="daterange"
                range-separator="至"
                :clearable="false"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </div>
          </el-form-item>
          <el-form-item label="" v-if="couponForm.validityType === 1">
            <div class="flx-default">
              <!-- <div class="width240">
                <el-input v-model="couponForm.delay" oninput="value=value.replace(/[^0-9.]/g,'')">
                  <template #prepend>领取后</template>
                  <template #append>天生效</template>
                </el-input>
              </div> -->
              <div class="width210">
                <el-input v-model="couponForm.validDay" oninput="value=value.replace(/[^0-9.]/g,'')">
                  <template #prepend>有效天数</template>
                  <template #append>天</template>
                </el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="可用周期" prop="cycleType">
            <el-radio-group v-model="couponForm.cycleType" @change="onChangeCycleType">
              <el-radio :label="0">每天</el-radio>
              <el-radio :label="1">每周</el-radio>
              <el-radio :label="2">每月</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            prop="cycelValue"
            v-if="couponForm.cycleType === 1"
            :rules="couponForm.cycleType === 1 ? couponRules.cycelValue : [{ required: false }]"
          >
            <div class="select-day-in-week-wrapper">
              <el-checkbox-group v-model="couponForm.cycelValue">
                <el-checkbox v-for="cycle in cycleData" :key="cycle.value" :label="cycle.value">{{ cycle.label }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item
            label=""
            prop="cycelValue"
            v-if="couponForm.cycleType === 2"
            :rules="couponForm.cycleType === 2 ? couponRules.cycelValue : [{ required: false }]"
          >
            <div class="select-day-in-week-wrapper">
              <el-checkbox-group v-model="couponForm.cycelValue">
                <el-checkbox v-for="day in 31" :key="'day' + day" :label="day">{{ day < 10 ? "0" + day : day }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <!-- <el-form-item label="可用时间段" prop="timespan">
            <el-radio-group v-model="couponForm.timespan">
              <el-radio :label="1">全天</el-radio>
              <el-radio :label="2">指定时段</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="">
            <div class="flx-column">
              <div class="flx-align-center mb10" v-for="(item, index) in couponForm.timespanlist" :key="index">
                <div class="width370">
                  <el-time-picker
                    v-model="item.timeRange"
                    is-range
                    range-separator="--"
                    format="HH:mm"
                    value-format="HH:mm"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                  />
                </div>
                <el-text class="ml20 pointer" type="danger" v-if="index !== 0">删除</el-text>
              </div>
              <div>
                <el-text class="pointer" type="danger" @click="addtimespan">添加时段</el-text>
                <el-text class="ml10" type="info">最多支持五个</el-text>
              </div>
            </div>
          </el-form-item> -->
          <el-form-item label="适用商品" prop="foodRange">
            <el-radio-group v-model="couponForm.foodRange">
              <el-radio :label="0">全部商品</el-radio>
              <el-radio :label="1">指定适用</el-radio>
              <el-radio :label="2">指定不适用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="couponForm.foodRange !== 0">
            <el-select class="width240" v-model="couponForm.appointType">
              <el-option label="指定菜品" :value="1" />
              <el-option label="指定类型" :value="2" />
            </el-select>
            <el-button class="ml10" type="primary" @click="onFoodData">{{
              couponForm.appointType === 1 ? "选择菜品" : "选择分类"
            }}</el-button>
          </el-form-item>
          <el-form-item
            v-if="couponForm.foodRange !== 0 && couponForm.appointType === 1"
            prop="foodList"
            :rules="couponForm.appointType === 1 ? couponRules.foodList : [{ required: false }]"
          >
            <el-table :data="couponForm.foodList" border style="width: 1000px">
              <el-table-column type="index" label="序号" width="100" />
              <el-table-column prop="name" label="菜品名称" align="lfet" />
              <el-table-column prop="foodTypeName" label="菜品类型" align="lfet" />
              <el-table-column prop="foodSpecName" label="菜品规格" align="lfet" />
              <el-table-column prop="posPrice" label="价格（元）" align="lfet" />
              <el-table-column prop="address" label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" @click="deleteSpecRow(scope.$index, 'food')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item
            v-if="couponForm.foodRange !== 0 && couponForm.appointType === 2"
            prop="foodcategoryList"
            :rules="couponForm.appointType === 2 ? couponRules.foodcategoryList : [{ required: false }]"
          >
            <el-table :data="couponForm.foodcategoryList" border style="width: 1000px">
              <el-table-column type="index" label="序号" width="100" />
              <el-table-column prop="name" label="分类名称" align="lfet" />
              <el-table-column prop="address" label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" @click="deleteSpecRow(scope.$index, 'type')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="每人每天限制" prop="isDayUseCount">
            <el-radio-group @change="onchange" v-model="couponForm.isDayUseCount">
              <el-radio label="不限制" :value="false" />
              <el-radio label="限制" :value="true" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="每人每天限制数量" prop="dayUseCount" v-if="couponForm.isDayUseCount">
            <el-input-number :min="1" v-model="couponForm.dayUseCount" :controls="false" />
          </el-form-item>
        </div>
        <!-- 优惠券使用规则 -->
        <div class="group">
          <div class="section-title">优惠券使用规则</div>
          <!-- <el-form-item label="券使用门槛设置" prop="threshold">
            <div class="flx-align-center">
              <el-radio-group v-model="couponForm.threshold">
                <el-radio :label="1">代金券</el-radio>
                <el-radio :label="2">商品兑换券</el-radio>
              </el-radio-group>
              <div class="ml20">
                <el-input v-model="couponForm.delay" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 300px">
                  <template #append>元，可使用一张优惠券</template>
                </el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="单笔订单最多可用" prop="threshold">
            <el-input v-model="couponForm.delay" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 300px">
              <template #append>张优惠券</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人每天最多可用" prop="threshold">
            <el-input v-model="couponForm.delay" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 300px">
              <template #append>张优惠券</template>
            </el-input>
          </el-form-item>
          <el-form-item label="叠加使用规则" prop="threshold">
            <el-radio-group v-model="couponForm.threshold">
              <el-radio :label="1">可与其他优惠券叠加使用</el-radio>
              <el-radio :label="2">不可与其他优惠券叠加使用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="活动同享规则" prop="threshold">
            <el-radio-group v-model="couponForm.threshold">
              <el-radio :label="1">可与其他优惠活动同享</el-radio>
              <el-radio :label="2">不可与其他优惠活动同享</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="转赠规则" prop="threshold">
            <el-radio-group v-model="couponForm.threshold">
              <el-radio :label="1">全部渠道</el-radio>
              <el-radio :label="2">部分渠道</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="优惠券可用渠道" prop="channelValue">
            <el-checkbox-group v-model="couponForm.channelValue">
              <el-checkbox :label="1">收银pos</el-checkbox>
              <el-checkbox :label="2">扫码点餐</el-checkbox>
              <el-checkbox :label="3">自营外卖</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="最低消费金额" prop="lowAmount">
            <el-input
              v-model="couponForm.lowAmount"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请填写"
              style="width: 320px"
            />
          </el-form-item>
          <!-- <el-form-item label="是否重复使用" prop="reusable">
            <el-radio-group v-model="couponForm.reusable">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </div>
        <!-- 其他设置 -->
        <div class="group">
          <div class="section-title">其他设置</div>
          <!-- <el-form-item label="券详细使用规则" prop="threshold">
            <el-radio-group v-model="couponForm.threshold">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="2">不显示</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="券说明" prop="description">
            <div class="width640">
              <el-input
                v-model="couponForm.description"
                :rows="2"
                type="textarea"
                placeholder="请填写优惠券介绍（C端用户可见。详细使用规则设置为“不显示”时，券说明为必填项）"
              />
            </div>
          </el-form-item>
          <el-form-item label="券备注" prop="remark">
            <div class="width640">
              <el-input v-model="couponForm.remark" :rows="2" type="textarea" placeholder="请填写优惠券备注（C端用户不可见）" />
            </div>
          </el-form-item>
          <!-- <el-form-item label="适用场景" prop="threshold">
            <el-radio-group v-model="couponForm.threshold">
              <el-radio :label="1">不限制</el-radio>
              <el-radio :label="2">仅收银POS的宴会订单可用</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </div>
      </el-form>
    </div>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
    <SelectTable @selected-list="handleSelectedList" ref="selectTableRef" />
  </div>
</template>
<script setup lang="tsx" name="couponEdit">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { formatDate } from "@/utils/date-formatter";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import SelectTable from "@/components/SelectTable/index.vue";
import { getFoodCategoryList, getGoodsList } from "@/api/modules/goods";
import { createFoodCoupon, getEditFoodCoupon, editFoodCoupon } from "@/api/modules/coupon";
import type { FormInstance } from "element-plus";
import { useSelectStore } from "@/stores/modules/dict";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);

interface CouponForm {
  id: number;
  name: string;
  typeId: number;
  parValue: any;
  validityType: number;
  cycleType: number;
  validityObject: any[];
  cycelValue: any[];
  foodRange: number;
  foodcategoryList: any[];
  foodList: any[];
  appointType: number;
  channelValue: number[];
  cycelValueObject: any[];
  lowAmount: string;
  validDay: number;
  reusable: number;
  description: string;
  remark: string;
  isDayUseCount: boolean;
  dayUseCount: number;
}
const couponForm = reactive<CouponForm>({
  id: 0,
  name: "",
  typeId: 1,
  parValue: null,
  validityType: 0,
  cycleType: 0,
  validityObject: [formatDate(0, "start", "yyyy-MM-dd"), formatDate(0, "end", "yyyy-MM-dd")],
  cycelValue: [],
  foodRange: 0,
  foodcategoryList: [],
  foodList: [],
  appointType: 1,
  channelValue: [1, 2, 3],
  cycelValueObject: [],
  lowAmount: "",
  validDay: 10,
  reusable: 1,
  description: "",
  remark: "",
  isDayUseCount: false,
  dayUseCount: 0
});
const couponRules = reactive({
  name: [{ required: true, message: "请填写优惠券名称" }],
  cycelValue: [{ required: true, message: "请选择可用周期" }],
  parValue: [{ required: true, message: "请输入券折扣/券面值" }],
  foodcategoryList: [{ required: true, message: "请选择类型" }],
  foodList: [{ required: true, message: "请选择菜品" }]
});

const cycleData = reactive([
  { label: "星期一", value: 1 },
  { label: "星期二", value: 2 },
  { label: "星期三", value: 3 },
  { label: "星期四", value: 4 },
  { label: "星期五", value: 5 },
  { label: "星期六", value: 6 },
  { label: "星期日", value: 7 }
]);

const onChangeCycleType = () => {
  couponForm.cycelValue = [];
};

const onFoodData = () => {
  if (couponForm.appointType === 1) {
    openSelectTreeTable("菜品选择");
  } else if (couponForm.appointType === 2) {
    openSelectTable("菜品分类选择");
  }
};

const changeTypeId = (value: string | number | boolean) => {
  if (value !== 2) {
    couponForm.parValue = null;
  }
};

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string) => {
  const params = {
    title,
    isView: false,
    index: 0,
    selTags: couponForm.foodList,
    columns: [
      { type: "selection", width: 80 },
      { prop: "name", label: "菜品名称", align: "left" },
      { prop: "foodTypeName", label: "分类" },
      { prop: "foodSpecName", label: "规格" },
      { prop: "posPrice", label: "菜品价格" }
    ],
    idName: "foodCategoryId",
    treeApi: getFoodCategoryList,
    api: getGoodsList
  };
  selectTreeTableRef.value?.acceptParams(params);
};

const handleSelectedTreeList = (val: any) => {
  couponForm.foodList = val.list;
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTable = (title: string) => {
  const params = {
    title,
    isView: false,
    selType: "selection",
    selTags: couponForm.foodcategoryList,
    columns: [
      { type: "selection", width: 80 },
      { prop: "name", label: "分类名称", align: "left" }
    ],
    api: getFoodCategoryList
  };
  selectTableRef.value?.acceptParams(params);
};
const handleSelectedList = (val: any) => {
  couponForm.foodcategoryList = val.list;
};

const deleteSpecRow = (index: number, ty: string) => {
  if (ty === "food") {
    couponForm.foodList.splice(index, 1);
  } else {
    couponForm.foodcategoryList.splice(index, 1);
  }
};
// const addtimespan = () => {
//   if (couponForm.timespanlist.length <= 5) {
//     couponForm.timespanlist.push({
//       timeRange: []
//     });
//   }
// };
const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editFoodCoupon(couponForm).then(() => {
          router.push({
            path: "/marketing/coupon",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createFoodCoupon(couponForm).then(() => {
          router.push({
            path: "/marketing/coupon",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

const couponType = ref<any[]>([]);
onMounted(() => {
  useSelectStore()
    .getDic("CouponType")
    .then(data => {
      couponType.value = data;
    });
  if (route.query.id) {
    isEdit.value = true;
    getEditFoodCoupon({ id: route.query.id }).then((res: any) => {
      Object.keys(couponForm).forEach((key: any) => {
        if (res.data.hasOwnProperty(key)) {
          couponForm[key] = res.data[key];
        }
      });
    });
  }
});
const onchange = () => {
  couponForm.dayUseCount = 0;
};
</script>

<style lang="scss" scoped>
.section-title {
  padding-left: 4px;
  margin-bottom: 26px;
  font-size: 14px;
  font-weight: 700;
  line-height: 14px;
  color: #333333;
  border-left: 4px solid var(--el-color-primary);
}
.select-day-in-week-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 638px;
  padding: 12px 14px;
  font-family: PingFangSC-Regular;
  color: #222222;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
